/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.me.home;

import android.app.Activity;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import com.threed.jpct.Animation;
import com.threed.jpct.Camera;
import com.threed.jpct.FrameBuffer;
import com.threed.jpct.Light;
import com.threed.jpct.Loader;
import com.threed.jpct.Logger;
import com.threed.jpct.Matrix;
import com.threed.jpct.Object3D;
import com.threed.jpct.Primitives;
import com.threed.jpct.RGBColor;
import com.threed.jpct.SimpleVector;
import com.threed.jpct.Texture;
import com.threed.jpct.TextureInfo;
import com.threed.jpct.TextureManager;
import com.threed.jpct.World;
import com.threed.jpct.util.MemoryHelper;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.Timer;
import java.util.logging.Level;
import java.util.zip.GZIPInputStream;
import java.util.zip.ZipInputStream;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.opengles.GL10;


/**
 *
 * @author Unni Vemanchery Mana
 */
public class GameActivity extends Activity {

        private static GameActivity master = null;
    	private GLSurfaceView mGLView;
	private MyRenderer renderer = null;
	private FrameBuffer fb = null;
	private World world = null;
	private RGBColor back = new RGBColor(50, 50, 100);

	private float touchTurn = 0;
	private float touchTurnUp = 0;

	private float xpos = -1;
	private float ypos = -1;

	private Object3D cube = null;
	private Object3D box = null;
	private Object3D newbox = null;
	private Object3D line3d = null;

	private int fps = 0;

	private Light sun = null;

	private float xDelta = 0.1f;
	private float yDelta = 0;
	private float zDelta = 0;


        private Timer textureTimer = null;
        private Texture waterTexture = null;
        private TextureInfo textureInfo1 = null;
        private TextureInfo textureInfo2 = null;
        QuadUV quaduv = new QuadUV();
        private Object3D water = null;
        private Object3D pole1 = null;
        private Object3D pole2 = null;
        private Object3D pole3 = null;
        private Object3D pole4 = null;
        private Matrix matrix = new Matrix();

        private float dx = 1.0f;

        private Object3D crab1 = null;

        private SimpleVector tmp = new SimpleVector();

        private int anim = 0;
	@Override
	protected void onCreate(Bundle savedInstanceState) {

		Logger.log("onCreate");

		if (master != null) {
			copy(master);
		}

		super.onCreate(savedInstanceState);
		mGLView = new GLSurfaceView(getApplication());
                // providing support for OpenGL ES 2.0
               //mGLView.setEGLContextClientVersion(2);

		mGLView.setEGLConfigChooser(new GLSurfaceView.EGLConfigChooser() {
			public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) {
				// Ensure that we get a 16bit framebuffer. Otherwise, we'll fall
				// back to Pixelflinger on some device (read: Samsung I7500)
				int[] attributes = new int[] { EGL10.EGL_DEPTH_SIZE, 16, EGL10.EGL_NONE };
				EGLConfig[] configs = new EGLConfig[1];
				int[] result = new int[1];
				egl.eglChooseConfig(display, attributes, configs, 1, result);
				return configs[0];
			}
		});

		renderer = new MyRenderer();
		mGLView.setRenderer(renderer);
		setContentView(mGLView);
	}

	@Override
	protected void onPause() {
		super.onPause();
		mGLView.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
		mGLView.onResume();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	private void copy(Object src) {
		try {
			Logger.log("Copying data from master Activity!");
			Field[] fs = src.getClass().getDeclaredFields();
			for (Field f : fs) {
				f.setAccessible(true);
				f.set(this, f.get(src));
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent me) {
		if (me.getAction() == MotionEvent.ACTION_DOWN) {
			xpos = me.getX();
			ypos = me.getY();
			return true;
		}

		if (me.getAction() == MotionEvent.ACTION_UP) {
			xpos = -1;
			ypos = -1;
			touchTurn = 0;
			touchTurnUp = 0;
			return true;
		}

		if (me.getAction() == MotionEvent.ACTION_MOVE) {
			float xd = me.getX() - xpos;
			float yd = me.getY() - ypos;
			xpos = me.getX();
			ypos = me.getY();
			touchTurn = xd / -100f;
			touchTurnUp = yd / -100f;
			return true;
		}
		try {
			Thread.sleep(15);
		} catch (Exception e) {
			// No need for this...
		}
		return super.onTouchEvent(me);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent msg) {
		if (keyCode == KeyEvent.KEYCODE_A) {
			return true;
		}
		return true;
	}


	protected boolean isFullscreenOpaque() {
		return true;
	}

	class MyRenderer implements GLSurfaceView.Renderer {

 	   private long time = System.currentTimeMillis();

		public MyRenderer(){
                    
		}

		public void onSurfaceChanged(GL10 gl, int w, int h) {
			if (fb != null) {
			    fb.dispose();
			}

                        // providing support for Open GL ES 2.0
			fb = new FrameBuffer(gl, w, h);
                       //fb = new FrameBuffer(w, h);

			if (master == null) {
				world = new World();
				world.setAmbientLight(20, 20, 20);
				sun = new Light(world);
				sun.setIntensity(250, 250, 250);
	
				cube = Primitives.getCube(1);

                               Object3D sand = drawSand();
                               sand.translate(new SimpleVector(0,0,1));
                               sand.rotateX(45.0f);
                               sand.rotateMesh();
                               sand.clearRotation();
                               world.addObject(sand);

                                water = drawWater();
                                //water.translate(new SimpleVector(5,8,1));
                                water.translate(new SimpleVector(5,3,1));
                                world.addObject(water);

                                pole1 = drawPole(5.0f);
                                pole1.translate(new SimpleVector(-18.0f,0.0f,-4.0f));
                                pole1.translateMesh();
                                pole1.clearTranslation();
                                pole1.rotateX(-10.0f);
                                pole1.rotateMesh();
                                pole1.clearRotation();
                                world.addObject(pole1);

                                pole2 = drawPole(5.0f);
                                pole2.translate(new SimpleVector(20.0f,0.0f,-4.0f));
                                pole2.translateMesh();
                                pole2.clearTranslation();
                                pole2.rotateX(-10.0f);
                                pole2.rotateMesh();
                                pole2.clearRotation();
                                world.addObject(pole2);

                                pole3 = drawPole(2.5f);
                                pole3.translate(new SimpleVector(-19.0f,0.0f,17.0f));
                                pole3.translateMesh();
                                pole3.clearTranslation();
                                pole3.rotateX(-10.0f);
                                pole3.rotateMesh();
                                pole3.clearRotation();
                                world.addObject(pole3);

                                pole4 = drawPole(2.5f);
                                pole4.translate(new SimpleVector(20.0f,0.0f,17.0f));
                                pole4.translateMesh();
                                pole4.clearTranslation();
                                pole4.rotateX(-10.0f);
                                pole4.rotateMesh();
                                pole4.clearRotation();
                                world.addObject(pole4);

                                // drawing crab
                                crab1 = drawCrabs();
                                crab1.setCollisionMode(Object3D.COLLISION_CHECK_SELF);
                                //crab1.setScale(0.31f);
                                crab1.scale(0.38f);
                                //crab1.translate(new SimpleVector(5f,-1f,1f)); //this is working
                                //crab1.translate(new SimpleVector(5f, -1f, -120f)); //this is working
                                crab1.translate(new SimpleVector(5f, -8f, -120f)); //this is working
                                crab1.translateMesh();
                                crab1.clearTranslation();
                                world.addObject(crab1);

				// adding one more cube
				//world.addObject(cube);
                                
				Camera cam = world.getCamera();
				//cam.moveCamera(Camera.CAMERA_MOVEOUT, 50);
                                cam.setFOV(2);
				//cam.lookAt(cube.getTransformedCenter());
                                setCamera();
                                System.out.println(" which side camera is looking at : " + cam.getDirection().x + ", " + cam.getDirection().y + "," + cam.getDirection().z);


				SimpleVector sv = new SimpleVector();
				sv.set(cube.getTransformedCenter());
				sv.y -= 100;
				sv.z -= 100;
				sun.setPosition(sv);
                                world.compileAllObjects(fb);
                                world.buildAllObjects();
				MemoryHelper.compact();
				if (master == null) {
					Logger.log("Saving master Activity!");
					master = GameActivity.this;
				}
                               // starting a timer task
			}
		}

		public void onSurfaceCreated(GL10 gl, EGLConfig config) {
		}

		public void onDrawFrame(GL10 gl) {
			if (touchTurn != 0) {
				touchTurn = 0;
				yDelta += 0.02f;
			}
			if (touchTurnUp != 0) {
			    touchTurnUp = 0;
			}

                        // animating the model to walk
                        crab1.animate(anim, crab1.getAnimationSequence().getSequence("walk"));
                        anim += 0.1f;
                        if (anim >= 1)
                        anim = 0;
                        // end of animation
                        
			fb.clear(back);
			world.renderScene(fb);
			world.draw(fb);
			fb.display();
			if (System.currentTimeMillis() - time >= 1000) {
				// Logger.log(fps + "fps");
				fps = 0;
				time = System.currentTimeMillis();
			}
			fps++;
                       // createWaterMoveEffect();
		}

  private Object3D drawSand() {
     Object3D sand   = Primitives.getPlane(2,20);
     Bitmap image    = BitmapFactory.decodeResource(getResources(), R.drawable.sand);
     Texture texture = new Texture(image);
     TextureManager.getInstance().addTexture("sand", texture);
     sand.setTexture("sand");
     sand.build();
     return sand;
  }

  private Object3D drawWater() {
     Object3D water = Primitives.getPlane(1,140);
     Bitmap image   = BitmapFactory.decodeResource(getResources(), R.drawable.water);
     waterTexture   = new Texture(image);
     TextureManager.getInstance().addTexture("water", waterTexture);
     water.setTexture("water");
     water.build();
     return water;
  }

   private void createWaterMoveEffect() {
     System.out.println(" inside the createWaterMoveEffect()....")   ;
     for(int i = 0; i<10; i++) {
       quaduv.setU1(i);
       quaduv.setV1(i + 2);
     }
     textureInfo1 = new TextureInfo(TextureManager.getInstance().getTextureID("water"), quaduv.getU1(), quaduv.getV1(),quaduv.getU2(),quaduv.getV2(), quaduv.getU3(), quaduv.getV3());
     textureInfo2 = new TextureInfo(TextureManager.getInstance().getTextureID("water"), quaduv.getU3(), quaduv.getV3(),quaduv.getU4(),quaduv.getV4(), quaduv.getU1(), quaduv.getV1());
     water.getPolygonManager().setPolygonTexture(0, textureInfo1);
     water.getPolygonManager().setPolygonTexture(1, textureInfo2);
   //  water.compile(true, true)
     water.touch();
   }

   private void createWaterMoveEffect1() {
      // System.out.println(" texture x: " + matrix.getTranslation().x);
       if(matrix.getTranslation().x > 15) {
           //SimpleVector sv = matrix.getTranslation();
           //sv.set(1.0f, 0.0f, 0.0f);
           //matrix.getTranslation().x = 1.0f;
           //matrix.translate(1.0f, 0.0f, 0.0f);
           matrix = new Matrix();
       }
       matrix.translate(1.0f, 0.0f, 0.0f);
       water.setTranslationMatrix(matrix);
       //water.setTextureMatrix(matrix);
       //dx = dx + 1;
   }

   private Object3D createPlane(){
     Object3D plane = new Object3D(30);
     Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.sand);
     Texture texture = new Texture(image);
//     TextureManager.getInstance().addTexture("water",texture);
     int textid = TextureManager.getInstance().getTextureID("sand");
     TextureInfo info = new TextureInfo(textid);
     plane.addTriangle(new SimpleVector(-30,30,0), new SimpleVector(30,30,0), new SimpleVector(30,-30,0),info);
     plane.addTriangle(new SimpleVector(30,-30,0), new SimpleVector(-30,-30,0), new SimpleVector(-30,30,0),info);
     return plane;
   }

   private Object3D drawPole(float scale){
       Object3D pole = Primitives.getCylinder(scale);
       pole.setAdditionalColor(RGBColor.RED);
       return pole;
   }

   private Object3D drawCrabs(){
       Object3D crab = null;
       Resources res = getResources();
       crab = Loader.loadSerializedObject(res.openRawResource(R.raw.crab));
       Bitmap image = BitmapFactory.decodeResource(res, R.drawable.crab1);
       Texture texture = new Texture(image);
       TextureManager.getInstance().addTexture("crabone", texture);
       crab.setTexture("crabone");
       crab.build();
       return crab;
   }

   private void setCamera() {
     SimpleVector p = crab1.getTranslation(tmp);
     Camera camera = world.getCamera();
     p.x = 5;
     p.y = -8;
     p.z = -60;
     camera.setPosition(p);
   }

   private Object3D drawNativeCube(){
    Object3D box = new Object3D(12);

    SimpleVector upperLeftFront=new SimpleVector(-1,-1,-1);
    SimpleVector upperRightFront=new SimpleVector(1,-1,-1);
    SimpleVector lowerLeftFront=new SimpleVector(-1,1,-1);
    SimpleVector lowerRightFront=new SimpleVector(1,1,-1);

    SimpleVector upperLeftBack = new SimpleVector( -1, -1, 1);
    SimpleVector upperRightBack = new SimpleVector(1, -1, 1);
    SimpleVector lowerLeftBack = new SimpleVector( -1, 1, 1);
    SimpleVector lowerRightBack = new SimpleVector(1, 1, 1);

    // Front
    box.addTriangle(upperLeftFront,0,0, lowerLeftFront,0,1, upperRightFront,1,0);
    box.addTriangle(upperRightFront,1,0, lowerLeftFront,0,1, lowerRightFront,1,1);

    // Back
    box.addTriangle(upperLeftBack,0,0, upperRightBack,1,0, lowerLeftBack,0,1);
    box.addTriangle(upperRightBack,1,0, lowerRightBack,1,1, lowerLeftBack,0,1);

    // Upper
    box.addTriangle(upperLeftBack,0,0, upperLeftFront,0,1, upperRightBack,1,0);
    box.addTriangle(upperRightBack,1,0, upperLeftFront,0,1, upperRightFront,1,1);

    // Lower
    box.addTriangle(lowerLeftBack,0,0, lowerRightBack,1,0, lowerLeftFront,0,1);
    box.addTriangle(lowerRightBack,1,0, lowerRightFront,1,1, lowerLeftFront,0,1);

    // Left
    box.addTriangle(upperLeftFront,0,0, upperLeftBack,1,0, lowerLeftFront,0,1);
    box.addTriangle(upperLeftBack,1,0, lowerLeftBack,1,1, lowerLeftFront,0,1);

    // Right
    box.addTriangle(upperRightFront,0,0, lowerRightFront,0,1, upperRightBack,1,0);
    box.addTriangle(upperRightBack,1,0, lowerRightFront, 0,1, lowerRightBack,1,1);

    box.build();
    box.setAdditionalColor(RGBColor.RED);
    return box;
   }
}
}

